package com.zwy.Shopping.servlet_;

import com.zwy.Shopping.dao.OrderDao;
import com.zwy.Shopping.dao.OrderItemDao;
import com.zwy.Shopping.dao.ProductDao;
import com.zwy.Shopping.dao.impl.OrderDaoImpl;
import com.zwy.Shopping.dao.impl.OrderItemDaoImpl;
import com.zwy.Shopping.dao.impl.ProductDaoImpl;
import com.zwy.Shopping.model.OrderItem;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.List;

@WebServlet("/cancel_order")
public class CancelOrderServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取取消订单的参数
        String orderIdStr = request.getParameter("OrderId");
        System.out.println(orderIdStr);
        if (orderIdStr == null || orderIdStr.isEmpty()) {
            // 如果未获取到 OrderId，返回错误信息
            response.setContentType("text/plain");
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().write("没有获取到订单信息");
            return;
        }

        int orderId ;
        try {
            //异常处理,当orderIdStr不能转化为整数
            orderId = Integer.parseInt(orderIdStr);
        } catch (NumberFormatException e) {
            // 如果 OrderId 不是整数，返回错误信息
            response.setContentType("text/plain");
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().write("订单信息格式不正确");
            return;
        }
        ProductDao productDao = new ProductDaoImpl();
        OrderItemDao orderItemDao = new OrderItemDaoImpl();
        //获得对应订单的订单明细
        List<OrderItem> orderItems = orderItemDao.getOrderItemByOrderId(orderId);
        for (OrderItem orderItem : orderItems){
            //将对应的商品的库存恢复
            productDao.IncreaseProductStock(orderItem.getProduct().getId(),orderItem.getQuantity());
        }

        // 取消订单
        OrderDao orderDao = new OrderDaoImpl();
        boolean success = orderDao.cancelOrder(orderId);
     //   response.sendRedirect("order.jsp");
        if(success){
            System.out.println("删除成功");
        }else{
            System.out.println("删除失败");
        }
    }
}